package com.ykq;

import java.io.*;
import java.net.*;

public class SimpleTCPServer {
    public static void main(String[] args) {
        int port = 9999; // 监听的端口号
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("服务器启动，在端口 " + port + " 上监听...");
            while (true) {
                Socket socket = serverSocket.accept(); // 等待客户端连接
                new Thread(new ClientHandler(socket)).start(); // 处理每个客户端连接
            }
        } catch (IOException e) {
            System.err.println("服务器启动失败: " + e.getMessage());
        }
    }

    private static class ClientHandler implements Runnable {
        private final Socket socket;

        public ClientHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
                String receivedMessage;
                while ((receivedMessage = in.readLine()) != null) {
                    System.out.println("接收到消息: " + receivedMessage);
                }
            } catch (IOException e) {
                System.err.println("处理客户端连接时出错: " + e.getMessage());
            }
        }
    }
}
